package com.hcms.common.exception;

import com.hcms.common.api.CommonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLSyntaxErrorException;

@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 处理数据库异常
     */
    @ExceptionHandler(SQLSyntaxErrorException.class)
    public ResponseEntity<CommonResponse<Object>> handler(SQLSyntaxErrorException exception) {
        logger.error("SQLSyntaxErrorException: {}", exception.getMessage());
        return CommonResponse.badRequest("数据库访问异常");
    }

    /**
     * 处理参数校验失败
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<CommonResponse<Object>> handler(MethodArgumentNotValidException exception) {
        String defaultMessage = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        logger.error("MethodArgumentNotValidException: {}", defaultMessage);
        return CommonResponse.badRequest(defaultMessage);
    }

    /**
     * 处理拒绝访问异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<CommonResponse<Object>> handler(AccessDeniedException exception) {
        logger.error("AccessDeniedException: {}", exception.getMessage());
        return CommonResponse.forbidden("禁止访问");
    }

    /**
     * 处理自定义的异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(ApiException.class)
    public ResponseEntity<CommonResponse<Object>> handler(ApiException exception) {
        logger.error("ApiException: {}", exception.getMessage());
        return CommonResponse.badRequest(exception.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<CommonResponse<Object>> handler(RuntimeException exception) {
        logger.error("RuntimeException: {}", exception.getMessage());
        exception.printStackTrace();
        return CommonResponse.badRequest(exception.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<CommonResponse<Object>> handler(Exception exception) {
        logger.error("Exception: {}", exception.getMessage());
        return CommonResponse.badRequest(exception.getMessage());
    }
}
